#include "device_syntaxhighlight.h"
#include <QDebug>

DeviceSyntaxHighlight::DeviceSyntaxHighlight(QTextDocument* parent)
    : QSyntaxHighlighter(parent)
{
    this->initRules();
}

void DeviceSyntaxHighlight::highlightBlock(const QString& text)
{
    for (const _HightRule& rule : _rules) {
        QRegularExpressionMatchIterator matchItr = rule.pattern.globalMatch(text);
        while (matchItr.hasNext()) {
            QRegularExpressionMatch match = matchItr.next();
            setFormat(match.capturedStart(), match.capturedLength(), rule.format);
        }
    }
}

void DeviceSyntaxHighlight::initRules()
{
    _HightRule rule;

    // 时间
    rule.format.setForeground(Qt::darkGray);
    rule.format.setFontFamilies({"Consolas"});
    rule.format.setBackground(Qt::lightGray);
    rule.pattern.setPattern("\\[.*\\]");
    _rules << rule;

    // 温度 key
    rule = {};
    rule.format.setForeground(QColor(180, 30, 110));
    rule.format.setFontWeight(QFont::Bold);
    rule.format.setFontFamilies({"Consolas"});
    rule.pattern.setPattern("\\bTemperature\\b");
    _rules << rule;

    // 温度 value
    rule = {};
    rule.format.setForeground(QColor(180, 30, 110));
    rule.format.setFontFamilies({"Consolas"});
    rule.pattern.setPattern("(?<=:)\\s*-?\\d+°C");
    _rules << rule;

    // 湿度 key
    rule = {};
    rule.format.setForeground(QColor(97, 54, 134));
    rule.format.setFontFamilies({"Consolas"});
    rule.pattern.setPattern("\\bHumidity\\b");
    _rules << rule;

    // 湿度 value
    rule = {};
    rule.format.setForeground(QColor(97, 54, 134));
    rule.format.setFontFamilies({"Consolas"});
    rule.pattern.setPattern("(?<=:)\\s*\\d+%");
    _rules << rule;

    // 报警-正常
    rule = {};
    rule.format.setForeground(Qt::darkGreen);
    rule.format.setFontFamilies({"Consolas"});
    rule.pattern.setPattern("\\(Normal\\)");
    _rules << rule;

    // 报警下限
    rule = {};
    rule.format.setForeground(Qt::white);
    rule.format.setBackground(Qt::darkBlue);
    rule.format.setFontWeight(QFont::Bold);
    rule.format.setFontFamilies({"Consolas"});
    rule.pattern.setPattern("\\(↓Lower\\)");
    _rules << rule;

    // 报警上限
    rule = {};
    rule.format.setForeground(Qt::white);
    rule.format.setBackground(QColor(220, 50, 50));
    rule.format.setFontWeight(QFont::Bold);
    rule.format.setFontFamilies({"Consolas"});
    rule.pattern.setPattern("\\(↑Upper\\)");
    _rules << rule;
}
